package com.itheima.service.impl;

import com.itheima.mapper.MemberMapper;
import com.itheima.mapper.OrderMapper;
import com.itheima.mapper.OrderSettingMapper;
import com.itheima.pojo.Member;
import com.itheima.pojo.Order;
import com.itheima.pojo.SubmitOrder;
import com.itheima.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class OrderServiceImpl implements OrderService {

    //    @Autowired
//    private RedisService redisService;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderSettingMapper orderSettingMapper;
    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private RedisTemplate redisTemplate;


    //根据预约id查询预约信息
    @Override
    public Order findById(String id) {
        return orderMapper.findById(id);
    }

    /**
     * 提交预约
     *
     * @param submitOrder
     * @return
     */
    @Override
    @Transactional
    public Integer submitOrder(SubmitOrder submitOrder) {

        String idCard = submitOrder.getIdCard();
        String name = submitOrder.getName();
        String orderDate = submitOrder.getOrderDate();
        Long setmealId = submitOrder.getSetmealId();
        String sex = submitOrder.getSex();
        String telephone = submitOrder.getTelephone();
        String validateCode = submitOrder.getValidateCode();

        // 1. 验证码校验

        // 1.1 生成随机验证码(模拟收到的验证码)
        Random random = new Random();
        int smsCode = 1000 + random.nextInt(9000); // 生成四位随机数

        // 1.2 保存验证码到 Redis，并设置过期时间为 5 分钟
        String redisKey = "validate_code:" + smsCode;
        redisTemplate.opsForValue().set(redisKey, smsCode, 5, TimeUnit.MINUTES);

        // 1.3 从 Redis 中获取验证码并进行验证
        String key = "validate_code:" + smsCode;
        String storedCode = (String) redisTemplate.opsForValue().get(key);

        if (!(storedCode != null && storedCode.equals(validateCode))) {
            throw new RuntimeException("验证码错误");
        }

        // 2. 预约日期的预约人数没有设置的话不能预约。
        Integer number = orderSettingMapper.findNumberByDate(orderDate);
        if (number == null || number == 0) {
            throw new RuntimeException("预约人数没有设置无法预约");
        }

        // 3. 预约日期是否已经约满，如果已经约满则无法预约
        Integer reservations = orderSettingMapper.findReservations(orderDate);
        if (reservations.equals(number)) {
            throw new RuntimeException("预约日期已约满无法预约");
        }

        // 4. 不能重复预约（同一个用户在同一天预约了同一个套餐）
        Integer[] findMemberIds = orderMapper.findMemberId(orderDate, setmealId);
        if (findMemberIds.length > 1) {
            throw new RuntimeException("不能重复预约");
        }

        // 5. 注册非会员用户
        Member member = memberMapper.findMember(idCard);
        if (member == null) {
            LocalDateTime regTime = LocalDateTime.now();
            memberMapper.registerMember(name, sex, idCard, telephone, regTime);
        }

        // 6. 更新已预约人数
        // 6.1 预约人数+1
        orderSettingMapper.updataReservations(orderDate);
        // 6.2 获取更新后的预约人数
        Integer reservationCount = orderSettingMapper.getReservations(orderDate);
        // 6.3 向t_order表中添加预约信息
        member = memberMapper.findMember(idCard);
        orderMapper.add(member.getId(), orderDate, setmealId);

        return reservationCount;
    }
}
